class Cpanel::MachineGridsController < Cpanel::BaseController
  before_action :set_machine_grid, only: [:show, :edit, :update, :destroy]

  def index
    respond_to do |format|
      format.html
      # TODO 解决n+1问题
      format.json { render json: MachineGridsDatatable.new(view_context, current_admin) }
    end
  end

  def show; end

  def new
    @machine_grid = MachineGrid.new
  end

  def edit; end

  def create
    @machine_grid = MachineGrid.new(machine_grid_params)

    respond_to do |format|
      if @machine_grid.save
        format.html { redirect_to cpanel_machine_grid_path(@machine_grid), notice: '保存成功' }
        format.json { render :show, status: :created, location: @machine_grid }
      else
        format.html { render :new }
        format.json { render json: @machine_grid.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @machine_grid.update(machine_grid_params)
        format.html { redirect_to cpanel_machine_grid_path(@machine_grid), notice: '保存成功' }
        format.json { render :show, status: :ok, location: @machine_grid }
      else
        format.html { render :edit }
        format.json { render json: @machine_grid.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @machine_grid.destroy
    render js: 'CPANEL.MachineGrids.DataTable.refresh();CPANEL.alert_success("删除成功");'
  end

  private

  def set_machine_grid
    @machine_grid = MachineGrid.find(params[:id])
  end

  def machine_grid_params
    params.require(:machine_grid).permit(:status, :grid_id, :machine_id, :product_id)
  end
end
